<template>
    <el-dialog title="添加" :visible.sync="dialogFormVisible"
        :close-on-click-modal=this.$store.state.theme.interface.other.closeOnClickModal width="55%">
        <el-form ref="form" :model="form" :rules="rules" label-width="80px" size="small">
            <el-form-item label="标题" prop="title">
                <el-input v-model="form.title" placeholder="请输入标签名称"></el-input>
            </el-form-item>
            <el-form-item label="作者" prop="author">
                <el-input v-model="form.author" placeholder="请输入标签名称"></el-input>
            </el-form-item>
            <el-form-item label="排序" prop="sort">
                <el-input v-model="form.sort" type="number" min="0" placeholder="排序（从大到小）"></el-input>
            </el-form-item>
            <el-form-item label="分类" prop="category_id">
                <el-select v-model="form.category_id" filterable placeholder="选择分类" style="display: block;">
                    <el-option v-for="item in categoryData" :key="item.id" :label="item.name" :value="item.id">
                    </el-option>
                </el-select>
            </el-form-item>
            <el-form-item label="状态" prop="status">
                <div class="block">
                    <el-radio v-model="form.status" label="1">草稿</el-radio>
                    <el-radio v-model="form.status" label="2">发布</el-radio>
                </div>
            </el-form-item>
            <el-form-item label="简介" prop="synopsis">
                <el-input type="textarea" v-model="form.synopsis" placeholder="请输入文章简介"></el-input>
            </el-form-item>
            <el-form-item label="封面" prop="cover_file_id">
                <div class="block">
                    <i v-if="!imageUrl" class="el-icon-plus material-select-btn" @click="clickSelectMaterialImg"></i>
                    <div v-if="imageUrl" class="material-box" @click="clickSelectMaterialImg">
                        <i class="el-icon-delete material-del-btn" @click.stop="clickDelMateriaImg"></i>
                        <el-image :src="imageUrl" class="material-img">
                            <div slot="error" class="image-slot">
                                <i class="el-icon-picture-outline"></i>
                            </div>
                        </el-image>
                    </div>
                </div>
            </el-form-item>
            <el-form-item label="内容" prop="content">
                <div style="border: 1px solid #ccc;">
                    <Toolbar style="border-bottom: 1px solid #ccc" :editor="editor" :defaultConfig="toolbarConfig" />
                    <Editor style="height: 350px; overflow-y: hidden;" v-model="form.content" :defaultConfig="editorConfig"
                        @onCreated="onCreated" />
                </div>
            </el-form-item>
        </el-form>
        <div slot="footer" class="dialog-footer">
            <el-button size="mini" @click="dialogFormVisible = false">取 消</el-button>
            <el-button size="mini" type="primary" @click="add()">确 定</el-button>
        </div>
        <x-material ref="material" :multiple=false title="选择封面" @changeMaterial="changeMaterial" />
    </el-dialog>
</template>
  
<style src="@wangeditor/editor/dist/css/style.css"></style>
<script>
import { add } from '@/api/info/article';
import { getAll } from '@/api/info/articleCategory';
import { Editor, Toolbar } from '@wangeditor/editor-for-vue'
import { config } from '@/config/config'

export default {
    name: "add",
    components: {
        'x-material': () => import('@/components/common/xMaterial'),
        Editor,
        Toolbar
    },
    data() {
        return {
            categoryData: [],
            imageUrl: '',
            form: {
                title: '',
                category_id: '',
                author: '',
                sort: 0,
                synopsis: '',
                cover_file_id: '',
                status: '1',
                content: ''
            },
            editor: null,
            toolbarConfig: {},
            editorConfig: {
                placeholder: '请输入内容...',
                MENU_CONF: {
                    uploadImage: {
                        fieldName: 'file',
                        server: config.requestApi + '/admin/common/Upload/upload',
                        meta: {
                            'is_vue': 1
                        },
                        headers: {
                            'Authorization': 'bearer ' + localStorage.getItem('token')
                        }
                    }
                }
            },
            rules: {
                title: [
                    { required: true, message: '请输入标题', trigger: 'blur' }
                ],
                author: [
                    { required: true, message: '请输入作者', trigger: 'blur' }
                ],
                category_id: [
                    { required: true, message: '请输选择分类', trigger: 'blur' }
                ],
                status: [
                    { required: true, message: '请输选择状态', trigger: 'blur' }
                ],
                synopsis: [
                    { required: true, message: '请输入简介', trigger: 'blur' }
                ],
                cover_file_id: [
                    { required: true, message: '请选择封面', trigger: 'blur' }
                ],
                content: [
                    { required: true, message: '请输入内容', trigger: 'blur' }
                ]
            },
            dialogFormVisible: false
        }
    },
    mounted() {
        this.initCategoryData();
    },
    methods: {
        initCategoryData() {
            getAll().then(res => {
                this.categoryData = res.data
            })
        },
        onCreated(editor) {
            this.editor = Object.seal(editor)//一定要用 Object.seal(),否则会报错
        },
        add() {
            if (this.editor.getText() === '') {
                this.$message.error('请输入内容');
                return;
            }
            this.$refs['form'].validate((valid) => {
                if (valid) {
                    add(this.form).then(res => {
                        this.dialogFormVisible = !this.dialogFormVisible;
                        this.$message({
                            message: res.msg,
                            type: 'success'
                        });
                        this.$emit('updateList');
                    })
                } else {
                    console.log('error submit!!');
                    return false;
                }
            });
        },
        clickSelectMaterialImg() {
            this.$refs.material.dialogFormVisible = true;
        },
        changeMaterial(material) {
            this.imageUrl = material[0].url;
            this.form.cover_file_id = material[0].id;
        },
        clickDelMateriaImg() {
            this.imageUrl = this.form.cover_file_id = '';
        }
    },
    beforeDestroy() {
        const editor = this.editor
        if (editor == null) return
        editor.destroy() // 组件销毁时，及时销毁编辑器
    },
    watch: {
        'dialogFormVisible': {
            handler: function () {
                this.$nextTick(() => {
                    this.$refs['form'].resetFields()
                    this.imageUrl = ''
                });
            }
        }
    }
}
</script>
  
<style lang="less" scoped>
.main-box {
    background-color: white;
    height: 100%;
    padding: 15px 30px;
    box-sizing: border-box;

    .material-select-btn {
        cursor: pointer;
    }

    .material-box {
        width: 100px;
        height: 100px;
        padding: 2px;
        border-radius: 50%;
        border: 1px solid var(--borderGrey);
        box-sizing: border-box;
        position: relative;
        cursor: pointer;

        &:hover {
            border: 1px solid var(--borderBlue);
        }

        .material-del-btn {
            position: absolute;
            top: 5px;
            right: 5px;
            color: red;
            font-size: 12px;
            z-index: 99;
            border-radius: 50%;
            border: 1px solid var(--borderGrey);
            background-color: white;
            padding: 2px;
            box-sizing: border-box;
            cursor: pointer;

            &:hover {
                border: 1px solid red;
            }
        }

        .material-select-btn {
            cursor: pointer;
        }

        .material-img {
            width: 100%;
            height: 100%;
            border-radius: 50%;
            box-sizing: border-box;
        }
    }
}
</style>